package com.djj.nanny.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import com.djj.nanny.service.ChatService;
import com.djj.nanny.util.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/chat/{userId}")
@Component
public class ChatWebSocketServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChatWebSocketServer.class);
    
    private static final Map<Long, Session> sessionMap = new ConcurrentHashMap<>();
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    private ChatService chatService;
    private Long userId;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        LOGGER.info("尝试建立WebSocket连接: userId={}, sessionId={}", userId, session.getId());
        try {
        this.chatService = SpringContextUtil.getBean(ChatService.class);
        this.userId = userId;
        sessionMap.put(userId, session);
            LOGGER.info("WebSocket连接成功建立: userId={}, sessionId={}", userId, session.getId());
        
        // 发送连接成功消息
            Map<String, Object> response = new HashMap<>();
            response.put("type", "connected");
            response.put("userId", userId);
            session.getBasicRemote().sendText(objectMapper.writeValueAsString(response));
            LOGGER.info("已发送连接成功消息: userId={}", userId);
        } catch (Exception e) {
            LOGGER.error("WebSocket连接建立失败: userId=" + userId, e);
        }
    }

    @OnClose
    public void onClose() {
        Session session = sessionMap.get(userId);
        LOGGER.info("WebSocket连接关闭: userId={}, sessionId={}", userId, session != null ? session.getId() : "unknown");
        sessionMap.remove(userId);
    }

    @OnMessage
    public void onMessage(String message) {
        try {
            LOGGER.info("收到WebSocket消息: userId={}, message={}", userId, message);
            chatService.handleMessage(message, userId);
        } catch (Exception e) {
            LOGGER.error("处理WebSocket消息失败: ", e);
            // 发送错误消息给客户端
            try {
                Map<String, Object> response = new HashMap<>();
                response.put("type", "error");
                response.put("message", "处理消息失败");
                Session session = sessionMap.get(userId);
                if (session != null && session.isOpen()) {
                    session.getBasicRemote().sendText(objectMapper.writeValueAsString(response));
                }
            } catch (IOException ex) {
                LOGGER.error("发送错误消息失败: ", ex);
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        LOGGER.error("WebSocket发生错误: userId={}, sessionId={}, error={}", userId, session.getId(), error.getMessage(), error);
    }

    // 发送消息给指定用户
    public static void sendMessage(Long userId, String message) {
        Session session = sessionMap.get(userId);
        if (session != null && session.isOpen()) {
            try {
                LOGGER.info("发送WebSocket消息: userId={}, message={}", userId, message);
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                LOGGER.error("发送WebSocket消息失败: ", e);
            }
        } else {
            LOGGER.warn("用户不在线或连接已关闭: userId={}", userId);
        }
    }
} 